<template>
  <page-container title="下单" :showBack="false">
    <view class="order-container">
      <!-- 标签页 -->
      <view class="tab-section">
        <view class="tab-item" :class="{ active: activeTab === 'GOLD' }" @click="switchTab('GOLD')">
          <text class="tab-text">黄金</text>
        </view>
        <!-- <view class="tab-item" :class="{ active: activeTab === 'SILVER' }" @click="switchTab('SILVER')">
        <text class="tab-text">白银</text>
      </view> -->
      </view>

      <!-- 价格信息 -->
      <view class="price-info">
        <view class="price-row">
          <view class="price-label">回购</view>
          <view class="price-value buyback">{{ formatNumber(realTimePrice.buyback) }}</view>
        </view>
        <view class="price-row">
          <view class="price-label">销售</view>
          <view class="price-value sales">{{ formatNumber(realTimePrice.sales) }}</view>
        </view>
        <view class="price-row">
          <view class="price-label">最高</view>
          <view class="price-value high">{{ formatNumber(realTimePrice.high) }}</view>
        </view>
        <view class="price-row">
          <view class="price-label">最低</view>
          <view class="price-value low">{{ formatNumber(realTimePrice.low) }}</view>
        </view>
      </view>

      <!-- 数量输入 -->
      <view class="quantity-section">
        <view class="quantity-row">
          <text class="quantity-label">预定重量(克)</text>
          <view class="quantity-input">
            <view class="input-btn" @click="decreaseQuantity">
              <text class="btn-text">-</text>
            </view>
            <input class="quantity-field" type="number" v-model="quantity" placeholder="100" min="100"
              @input="handleInput" @blur="handleBlur" />
            <view class="input-btn" @click="increaseQuantity">
              <text class="btn-text">+</text>
            </view>
          </view>
        </view>
        <view class="fee-row">
          <text class="fee-label">仓管费</text>
          <text class="fee-value">{{getManageFeeStandard()}}元/天</text>
        </view>
        <view class="total-row">
          <text class="total-label">货款总额</text>
          <text class="total-value">{{ totalAmount }}元</text>
        </view>
        <view class="fee-row">
          <text class="fee-label">须付定金</text>
          <text class="fee-value">{{ getDeposit() }}元</text>
        </view>


        <!-- 快捷选择 -->
        <view class="quick-select-section" v-if="activeTab === 'GOLD'">
          <text class="quick-select-label">快捷选择</text>
          <view class="quick-select-buttons">

            <view class="quick-select-btn" v-for="(item, index) in quickBuyWeightList" :key="index"
              :class="{ active: selectedQuickWeight === item.weight }" @click="selectQuickWeight(item.weight)">
              <text class="quick-select-text">{{ item.weightName }}</text>
            </view>

          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <view class="action-card sell" :class="{ active: selectedAction === 'SELL' }" @click="selectAction('SELL')">
          <text class="action-price">{{ formatNumber(realTimePrice.buyback) }}</text>
          <text class="action-label">当前回购价</text>
          <view class="action-btn sell-btn">
            <text class="btn-text">卖料</text>
          </view>
        </view>

        <view class="action-card buy" :class="{ active: selectedAction === 'BUY' }" @click="selectAction('BUY')">
          <text class="action-price">{{ formatNumber(realTimePrice.sales) }}</text>
          <text class="action-label">当前销售价</text>
          <view class="action-btn buy-btn">
            <text class="btn-text">买料</text>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <view class="submit-btn" @click="showConfirmDialog">
          <text class="submit-text">提交</text>
        </view>
      </view>

      <!-- 订单确认对话框 -->
      <OrderConfirmDialog :visible="showConfirm" :orderInfo="confirmOrderInfo" @close="hideConfirmDialog"
        @cancel="hideConfirmDialog" @confirm="handleConfirmOrder" />
    </view>
  </page-container>
</template>

<script>
import OrderConfirmDialog from '@/components/OrderConfirmDialog.vue'
import { checkBalance } from '@/utils/tools';
import { isLoggedIn, checkLogin } from '@/utils/auth';

export default {
  name: 'OrderPage',
  components: {
    OrderConfirmDialog
  },
  data() {
    return {
      quickBuyWeightList: [],
      activeTab: 'GOLD',
      quantity: 100,
	  defaultQuantity: 10,
      selectedAction: 'SELL', // 默认选中卖料
      selectedQuickWeight: 0,
      priceData: {
        GOLD: {
          buyback: '--',
          sales: '--',
          high: '--',
          low: '--'
        },
        SILVER: {
          buyback: '--',
          sales: '--',
          high: '--',
          low: '--'
        }
      },
      realTimePrice: {
        type: '',
        buyback: 0,
        sales: 0,
        high: 0,
        low: 0,
      },
      // 添加价格缓存，分别存储黄金和白银的最新价格
      priceCache: {
        GOLD: {
          type: 'GOLD',
          buyback: 0,
          sales: 0,
          high: 0,
          low: 0,
        },
        SILVER: {
          type: 'SILVER',
          buyback: 0,
          sales: 0,
          high: 0,
          low: 0,
        }
      },
      showConfirm: false,
      confirmOrderInfo: {
        materialType: 'GOLD',
        weight: 0,
        price: 0,
        totalAmount: 0,
        deposit: 0,
        orderType: 'BUY'
      },

    }
  },

  onUnload() {
    uni.$off('priceMessagesChanged');
  },
  onShow() {
    this.quickBuyWeight()
  },
  onLoad() {

    // 初始化价格显示
    this.initializePriceDisplay()
    uni.$on('priceMessagesChanged', (newMsg) => {
      // console.log(220, '下单页面:', newMsg.data.priceMap[this.activeTab]);
      const { materialType, sellPrice, price, maxPrice, minPrice } = newMsg.data.priceMap[this.activeTab];
      this.getRealTimePrice(materialType, sellPrice, price, maxPrice, minPrice)
    });
	if(uni.getStorageSync("appletConfig")){
		this.defaultQuantity = uni.getStorageSync("appletConfig").minWeight;
	}
	

  },
  computed: {
    totalAmount() {
      // 根据选择的操作类型决定使用哪个价格
      let price
      if (this.selectedAction === 'SELL') {
        // 卖料使用回购价
        price = parseFloat(this.realTimePrice.buyback)
      } else {
        // 买料使用销售价
        price = parseFloat(this.realTimePrice.sales)
      }
      const amount = price * this.quantity
      return this.formatNumber(amount.toFixed(2))
    }
  },
  methods: {
    // 格式化数字，添加千分符
    formatNumber(numStr) {
      if (!numStr || numStr === 'NaN' || numStr === 'Infinity' || numStr === '--') return '0.00';
      // 将数字字符串按小数点分割
      const parts = numStr.toString().split('.');
      // 对整数部分添加千分符
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      // 重新组合
      return parts.join('.');
    },

    // 初始化价格显示
    initializePriceDisplay() {
      // 根据当前选中的tab初始化价格显示
      if (this.activeTab === 'GOLD') {
        this.realTimePrice = {
          type: 'GOLD',
          buyback: this.priceData.GOLD.buyback,
          sales: this.priceData.GOLD.sales,
          high: this.priceData.GOLD.high,
          low: this.priceData.GOLD.low,
        }
      } else if (this.activeTab === 'SILVER') {
        this.realTimePrice = {
          type: 'SILVER',
          buyback: this.priceData.SILVER.buyback,
          sales: this.priceData.SILVER.sales,
          high: this.priceData.SILVER.high,
          low: this.priceData.SILVER.low,
        }
      }
    },

    getRealTimePrice(materialType, sellPrice, price, maxPrice, minPrice) {
      if (this.activeTab === 'GOLD') {
        if (materialType === 'GOLD') {
          // 更新价格缓存
          this.priceCache.GOLD = {
            type: 'GOLD',
            buyback: price,
            sales: sellPrice,
            high: maxPrice,
            low: minPrice,
          };
          // 如果当前选中的是黄金tab，立即更新显示
          if (this.activeTab === 'GOLD') {
            this.realTimePrice = { ...this.priceCache.GOLD };
          }
        }
      } else if (this.activeTab === 'SILVER') {
        if (materialType === 'SILVER') {
          // 更新价格缓存
          this.priceCache.SILVER = {
            type: 'SILVER',
            buyback: price,
            sales: sellPrice,
            high: maxPrice,
            low: minPrice,
          };
          // 如果当前选中的是白银tab，立即更新显示
          if (this.activeTab === 'SILVER') {
            this.realTimePrice = { ...this.priceCache.SILVER };
          }
        }
      }

      // 无论当前tab是什么，都更新对应类型的缓存
      if (materialType === 'GOLD') {
        this.priceCache.GOLD = {
          type: 'GOLD',
          buyback: price,
          sales: sellPrice,
          high: maxPrice,
          low: minPrice,
        };
      } else if (materialType === 'SILVER') {
        this.priceCache.SILVER = {
          type: 'SILVER',
          buyback: price,
          sales: sellPrice,
          high: maxPrice,
          low: minPrice,
        };
      }
    },
	getManageFeeStandard(){
		if(uni.getStorageSync("appletConfig")){
			return Number(uni.getStorageSync("appletConfig").manageFeeStandard).toFixed(2);
		}
		return 10;
	},
    // 获取定金
    getDeposit() {
      const deposit  = this.getDepositNum();
      return this.formatNumber(deposit.toFixed(2));
    },
    // 获取定金
    getDepositNum() {
		let deposit = Number(this.quantity) * 20;
		if(uni.getStorageSync("appletConfig")){
			deposit =  Number(this.quantity) * (Number(uni.getStorageSync("appletConfig").retainerStandard) /1000) ;
		}
		if(uni.getStorageSync("customerInfo")){
			if(uni.getStorageSync("customerInfo").retainerStandard){
				deposit =  Number(this.quantity) * (Number(uni.getStorageSync("customerInfo").retainerStandard) / 1000) ;
			}
		}
		return deposit;
      
    },
    switchTab(tab) {
      return
      this.activeTab = tab

      // 根据切换的tab立即从缓存中获取对应类型的最新价格
      if (tab === 'GOLD' && this.priceCache.GOLD.type) {
        // 切换到黄金tab，立即显示黄金的最新价格
        this.realTimePrice = { ...this.priceCache.GOLD }
      } else if (tab === 'SILVER' && this.priceCache.SILVER.type) {
        // 切换到白银tab，立即显示白银的最新价格
        this.realTimePrice = { ...this.priceCache.SILVER }
      }
      const goldPrice = uni.getStorageSync('material_price_gold')
      const silverPrice = uni.getStorageSync('material_price_silver')
      console.log(3333, goldPrice.priceData);
      console.log(4444, silverPrice.priceData);

      // 如果缓存中没有对应类型的价格数据，则使用默认价格
      if (!this.realTimePrice.type || this.realTimePrice.type === '') {
        if (tab === 'GOLD') {
          this.realTimePrice = {
            type: 'GOLD',
            buyback: goldPrice.priceData.sellPrice,
            sales: goldPrice.priceData.price,
            high: goldPrice.priceData.maxPrice,
            low: goldPrice.priceData.minPrice,
          }
        } else if (tab === 'SILVER') {
          this.realTimePrice = {
            type: 'SILVER',
            buyback: silverPrice.priceData.sellPrice,
            sales: silverPrice.priceData.price,
            high: silverPrice.priceData.maxPrice,
            low: silverPrice.priceData.minPrice,
          }
        }
      }
    },
    decreaseQuantity() {
      if (this.quantity > 1000) {
        this.quantity -= 1000;
      } else {
        this.quantity = 1000;
      }
    },
    increaseQuantity() {
      this.quantity += 1000;
    },
    handleInput(e) {
      // 只允许输入100的倍数，最小100，最大1000000
      let inputValue = e.detail.value;

      // 如果输入为空，设置为最小值
      if (!inputValue || inputValue === '') {
        this.quantity = this.defaultQuantity;
        return;
      }

      let value = parseInt(inputValue);

      // 如果解析失败，设置为最小值
      if (isNaN(value)) {
        this.quantity = this.defaultQuantity;
        return;
      }

      // 如果输入值小于100，设置为100
      if (value < this.defaultQuantity) {
        this.quantity = this.defaultQuantity;
        return;
      }

      // 如果输入值大于1000000，设置为1000000
      if (value > 1000000) {
        this.quantity = 1000000;
        return;
      }

      // 如果不是100的倍数，调整为最接近的100的倍数
      if (value % this.defaultQuantity !== 0) {
        value = Math.round(value / this.defaultQuantity) * this.defaultQuantity;
      }

      // 更新quantity值
      this.quantity = value;
    },

    handleBlur() {
      // 失去焦点时验证并修正数量值
      if (this.quantity < this.defaultQuantity) {
        this.quantity = this.defaultQuantity;
      } else if (this.quantity > 1000000) {
        this.quantity = 1000000;
      } else if (this.quantity % this.defaultQuantity !== 0) {
        this.quantity = Math.round(this.quantity / this.defaultQuantity) * this.defaultQuantity;
      }
    },
    // 快速购买重量选择
    quickBuyWeight() {
      this.$http.get('/applet/common/fastBuyWeight').then(res => {
        this.quickBuyWeightList = res.data || []
        this.selectedQuickWeight = this.quickBuyWeightList[0].weight
        this.quantity = this.quickBuyWeightList[0].weight
      })
    },
    selectQuickWeight(weight) {
      console.log('选择快捷重量:', weight);
	  this.selectedQuickWeight = weight;
      this.quantity = weight;
      
    },
    selectAction(action) {
      this.selectedAction = action
    },
    sellMaterial() {
      let params = {
        orderType: 'SELL',
        price: this.realTimePrice.buyback,
        weight: this.quantity,
        materialType: this.realTimePrice.type,
        cusId: uni.getStorageSync('customerInfo') ? uni.getStorageSync('customerInfo').id : '',
      }
      this.$http.post('/applet/customer/orders/create', JSON.stringify(params)).then(res => {
        uni.showToast({
          title: '卖料成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 100)
      })
    },
    buyMaterial() {
      let params = {
        orderType: 'BUY',
        weight: this.quantity,
        price: this.realTimePrice.sales,
        materialType: this.realTimePrice.type,
        cusId: uni.getStorageSync('customerInfo') ? uni.getStorageSync('customerInfo').id : '',
      }
      this.$http.post('/applet/customer/orders/create', JSON.stringify(params)).then(res => {
        uni.showToast({
          title: '买料成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 100)
      })
    },
    showConfirmDialog() {
		if (!checkLogin()) {
		  return;
		}
      this.confirmOrderInfo = {
        materialType: this.activeTab,
        weight: this.quantity,
        price: this.selectedAction === 'BUY' ? this.realTimePrice.sales : this.realTimePrice.buyback,
        totalAmount: this.totalAmount,
        deposit: 0.00,
        orderType: this.selectedAction
      }
      this.showConfirm = true
    },

    hideConfirmDialog() {
      this.showConfirm = false
    },

    handleConfirmOrder() {
      this.hideConfirmDialog()
      this.submitOrder()
    },
    async submitOrder() {
      // 检查余额是否足够支付定金
      const isBalanceSufficient = await checkBalance(this.getDepositNum())
      if (!isBalanceSufficient) {
        return
      }

      if (this.selectedAction === 'SELL') {
        this.sellMaterial()
      } else {
        this.buyMaterial()
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/uni.scss';

.order-container {
  min-height: 100vh;
  background-color: #F5F5F6;
  padding: 20rpx 26rpx;
}

/* 标签页 */
.tab-section {
  display: flex;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  position: relative;
}

.tab-text {
  font-size: 28rpx;
  color: #999999;
}

.tab-item.active .tab-text {
  color: #0B1F20;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #0B1F20;
  border-radius: 2rpx;
}

/* 价格信息 */
.price-info {
  padding: 20rpx 26rpx;
  background-color: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-row {
  // padding: 10rpx 0;
  text-align: center;
}

.price-row:last-child {
  border-bottom: none;
}

.price-label {
  font-size: 28rpx;
  color: #0B1F20;
  padding-bottom: 20rpx;
}

.price-value {
  font-size: 32rpx;
}

.buyback,
.sales,
.high {
  color: $uni-text-color-red;
}

.low {
  color: $uni-text-color-green;
}

/* 数量输入 */
.quantity-section {
  padding: 20rpx 26rpx;
  background-color: #ffffff;
  border-top: 1rpx solid #f0f0f0;
}

.quantity-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.quantity-label {
  font-size: 28rpx;
  color: #0B1F20;
}

.quantity-input {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  overflow: hidden;
}

.input-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #393837;
  border: 1rpx solid #393837;
}

.btn-text {
  font-size: 32rpx;
  color: #ffffff;
}

.quantity-field {
  width: 200rpx;
  height: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #0B1F20;
  background-color: #ffffff;
  border: 1rpx solid #393837;
}

/* 快捷选择样式 */
.quick-select-section {
  margin: 20rpx 0;
  border-top: 2rpx solid #EEEEEE;
  padding-top: 20rpx;
}

.quick-select-label {
  font-size: 28rpx;
  color: #D4A574;
  margin-bottom: 20rpx;
  display: block;
}

.quick-select-buttons {
  display: flex;
  gap: 20rpx;
}

.quick-select-btn {
  flex: 1;
  height: 60rpx;
  background-color: #E5E5E5;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.quick-select-btn.active {
  background-color: #393837;
}

.quick-select-text {
  font-size: 24rpx;
  color: #666666;
  transition: color 0.3s ease;
}

.quick-select-btn.active .quick-select-text {
  color: #D4A574;
}

.fee-row,
.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  color: #0B1F20;
  // padding-bottom: 20rpx;
  // padding-top: 10rpx;
}

.fee-label,
.total-label {
  font-size: 28rpx;
  color: #0B1F20;
}

.fee-value {
  font-size: 28rpx;
  color: #0B1F20;
}

.total-value {
  font-size: 32rpx;
  color: #0B1F20;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  padding: 20rpx 26rpx;
  gap: 20rpx;
}

.action-card {
  flex: 1;
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  text-align: center;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.action-card.active {
  border-color: #393837;
  background-color: #ffffff;
}

.action-price {
  display: block;
  font-size: 36rpx;
  color: $uni-text-color-orange;
  margin-bottom: 10rpx;
  transition: color 0.3s ease;
}

.action-label {
  display: block;
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 20rpx;
}

.action-btn {
  padding: 20rpx 26rpx;
  border-radius: 8rpx;
  background-color: #393837;
  transition: all 0.3s ease;
}

.action-btn .btn-text {
  color: #ffffff;
  font-size: 28rpx;
}

.action-card.active .action-btn {
  background-color: #393837;
}


/* 提交按钮 */
.submit-section {
  padding: 0rpx 26rpx;
  padding-bottom: 50rpx;
}

.submit-btn {
  padding: 20rpx 26rpx;
  background-color: #393837;
  border-radius: 12rpx;
  text-align: center;
}

.submit-text {
  color: #ffffff;
  font-size: 32rpx;
  letter-spacing: 2rpx;
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .order-container {
    padding-bottom: 120rpx;
  }
}
</style>